import { Fview } from "../gui/UIDefine";
import { IModule } from "../common/Common";
import game from "../game";
import UIConfig from "../config/UIConfig";
import SpineItem from "./SpineItem";

export class SpineManage implements IModule {

    private _templetMap: Set<string>;
    private _cacheSk = new Map<string, SpineItem>();

    private _lastClearTime: number = 0;

    public defaultParent: Fview;

    initialize(): void {
        this._templetMap = new Set<string>();
    }

    onTimeLoop(): void {
        if (game.second - this._lastClearTime < UIConfig.spineClearTime) {
            return;
        }

        this._lastClearTime = game.second;
        this.clearSpine();
    }

    /**
     * 创建一个骨骼动画
     * @param url 完整地址
     * @returns 
     */
    create(url: string) {

        let templet = Laya.Loader.getRes(url);
        let item = SpineItem.create();

        if (!!templet) {
            item.init(templet);
            return item;
        }

        this._templetMap.add(url);
        Laya.loader.load(url).then((elm) => {
            item.init(elm);
        }, () => {
            item.destroy();
        })

        return item;
    }

    /**
     * 创建一个带标识的动画，重复标识不会重复创建
     * @param flg 标识
     * @param sk 
     * @param ver 
     */
    createAndCache(flg: string, sk: string) {
        let item = this._cacheSk.get(flg);
        if (!item || item.destroyed) {
            item = this.create(sk);
            this._cacheSk.set(flg, item);
        }

        return item;
    }


    clearSkByFlg(flg: string) {

        if (this._cacheSk.has(flg)) {
            let item = this._cacheSk.get(flg);
            item.disposeNow();
            this._cacheSk.delete(flg);
        }
    }


    /**
     * 清理未引用动画
     */
    clearSpine() {

        let tempArr = [];
        this._templetMap.forEach((v) => {
            let templet = Laya.Loader.getRes(v);
            if (templet && templet.referenceCount <= 0) {
                tempArr.push(v);
            }
        });

        tempArr.forEach((v) => {
            this._templetMap.delete(v);
            Laya.Loader.getRes(v).destroy();
        });
    }

}